/**
 * 修改密码
 */

import { useCurrentUser, useReqBody } from "@sker/runtime";
import { useTransaction, HttpError, randomSalt, encryptPassword, toSuccess } from "@sker/core";
import { SysUser } from "@sker/entities";

import { z } from 'zod'
const Input = z.object({
    password: z.string({ description: '密码', required_error: '必填', invalid_type_error: '格式错误' }).min(6),
    newPassword: z.string({ description: '新密码', required_error: '必填', invalid_type_error: '格式错误' }).min(6, '最小长度为6').max(20, '最大长度为20'),
    reNewPassword: z.string({ description: '确认密码', required_error: '必填', invalid_type_error: '格式错误' }).min(6, '最小长度为6').max(20, '最大长度为20')
})
export async function change_password() {
    const body = Input.parse(useReqBody())
    if (body.newPassword !== body.reNewPassword) {
        throw new HttpError(`密码不一致`)
    }
    const [current] = useCurrentUser(true);
    return await useTransaction(async m => {
        const user = await m.findOne(SysUser, { where: { uid: current.id }, select: { uid: true, password: true, salt: true } })
        if (!user) throw new HttpError(`用户不存在活已删除`)
        const _isEqual = await passwordIsEqual(user.password, body.password, user.salt)
        if (!_isEqual) throw new HttpError(`密码错误`)
        const salt = randomSalt()
        const _encryptPassword = await encryptPassword(body.newPassword, salt)
        await m.update(SysUser, user.uid, { password: _encryptPassword, salt: salt })
        return toSuccess({ id: user.uid })
    })
}

async function passwordIsEqual(old: string, current: string, salt: string) {
    const currentEncrypt = await encryptPassword(current, salt)
    return currentEncrypt === old;
}

export default change_password;